package com.vf.cloud.paas.app.master.api.sys.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.jfinal.kit.StrKit;
import com.vf.cloud.paas.app.master.common.domain.RenderAgent;
import com.vf.cloud.paas.app.master.common.domain.RenderAgentGpu;
import com.vf.cloud.paas.app.master.common.domain.UserAgent;
import com.vf.cloud.paas.common.datasource.annotation.Tx;
import com.vf.cloud.paas.common.util.R;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/user/agent")
public class UserAgentController {

	@PostMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<List<RenderAgent>> list(HttpServletRequest request, @RequestBody UserAgent param) throws Exception {
		List<RenderAgent> renderAgents=RenderAgent.dao.find("select * from "+RenderAgent.TABLE_NAME);
		for(RenderAgent renderAgent:renderAgents) {
			List<RenderAgentGpu> renderAgentGpus=RenderAgentGpu.dao.find("select a.*,"
					+ " (CASE  WHEN (SELECT COUNT(*) AS COUNT FROM " + UserAgent.TABLE_NAME+ " WHERE user_id=? and agent_id=? and agent_gpu_index=a.index )>0 THEN 1 ELSE  0 END ) AS status  "
					+ " from "+RenderAgentGpu.TABLE_NAME+" a  ",param.getUserId(),renderAgent.getId());
		
			renderAgent.setChildren(renderAgentGpus);
		}
		return R.ok(renderAgents);
	}

	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<UserAgent> save(HttpServletRequest request,@RequestBody UserAgent param) {
		
		if (StrKit.equals(param.getStatus(), "1")) {
			if (param.save()) {
				return R.ok();
			}
		}
		if (StrKit.equals(param.getStatus(), "0")) {
			if (param.delete()) {
				return R.ok();
			}
		}
		return R.failed();
	}

}
